package com.example.ds.plugins;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {
                MappedStatement.class, Object.class
        }),
        @Signature(type = Executor.class, method = "query", args = {
                MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
        })
})
public class SlowSqlInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(SlowSqlInterceptor.class);
    /**
     * 慢SQL日志阈值
     */
    private static final long DEFAULT_THRESHOLD = 10;

    private long slowSqlThreshold = DEFAULT_THRESHOLD;

    public SlowSqlInterceptor() {
        this(DEFAULT_THRESHOLD);
    }

    public SlowSqlInterceptor(long slowSqlThreshold) {
        this.slowSqlThreshold = slowSqlThreshold;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = invocation.proceed();
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        // 执行时间超过阈值的SQL打印日志
        if (executionTime >= slowSqlThreshold) {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = invocation.getArgs()[1];
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            String sql = boundSql.getSql();
            logger.warn("⚠️ 发现慢SQL - {} - 耗时: {}ms (阈值: {}ms)",
                    sql, executionTime, slowSqlThreshold);
        }
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

}

